﻿using EPlantApp.Infrastructure.Models;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace EPlantApp.Infrastructure.Extensions
{
    public static class SugarExt
    {
        public static void AddSugar(this IServiceCollection services, List<DbConfig> dbConfigs)
        {
            foreach (DbConfig dbConfig in dbConfigs)
            {
                // 1. 创建 SqlSugar 配置
                var connectionConfig = new ConnectionConfig
                {
                    ConnectionString = dbConfig.ConnectionString,
                    DbType = (DbType)dbConfig.DbType,
                    IsAutoCloseConnection = dbConfig.IsAutoCloseConnection,
                    ConfigId = dbConfig.ConfigId
                };
                // 2. 通过反射创建 SqlSugarClient 实例

                // 3. 以 ConfigId 为名称注入到容器（支持后续按名称获取）
                // 注入接口 ISqlSugarClient + 名称标识
                services.AddSingleton<ISqlSugarClient>(serviceProvider => new SqlSugarClient(connectionConfig));
                //// 额外注入具体实例（可选，按名称区分多库）
                //services.AddSingleton(sqlSugarClientType, sqlSugarClient);
                //// 记录名称与实例的映射（便于按名称获取）
                //services.AddSingleton(new KeyValuePair<string, ISqlSugarClient>(dbConfig.ConfigId, sqlSugarClient));
            }
        }
    }
}
